/**
 * 
 */
package pt.mleiria.cryptographic.datahashing;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

/**
 * @author NB13712
 * It's a one way function
 */
public class CryptoHash implements Hasher {

	private Hash hash;
	private String fileName;
	private byte[] md;

	public byte[] getMd() {
		return md;
	}
	/**
	 * 
	 */
	public CryptoHash() {
	}
	/**
	 * 
	 * @param hash
	 * @param fileName
	 */
	public CryptoHash(final Hash hash, final String fileName) {
		this.hash = hash;
		this.fileName = fileName;
	}
	
	public void setHashName(Hash hash) {
		this.hash = hash;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public void messageDigest() throws NoSuchAlgorithmException, NoSuchProviderException, IOException{
		final MessageDigest md = MessageDigest.getInstance(this.hash.name());
		this.md = digestFile(md);
	}
	/**
	 * 
	 */
	public void messageDigest(final String provider) throws NoSuchAlgorithmException, NoSuchProviderException, IOException {
		final MessageDigest md = MessageDigest.getInstance(this.hash.name(), provider);
		this.md = digestFile(md);
	}
	/**
	 * 
	 * @param md
	 * @return
	 * @throws IOException
	 */
	private byte[] digestFile(final MessageDigest md) throws IOException{
		final FileInputStream fis = new FileInputStream(fileName);
		/*
		 * Reading in 8-kilobyte chunks 
		 */
		byte[] buffer = new byte[8192];
		int length;
		while((length = fis.read(buffer)) != -1){
			md.update(buffer, 0, length);
		}
		fis.close();
		return md.digest();
	}
	/**
	 * Message digest coded in hexa
	 * @return
	 */
	public String getMessageDigestHex(){
		return Hex.encodeHexString(md);
	}
	/**
	 * Base64 is a system for representing an array of bytes as ASCII characters
	 * @return
	 */
	public String getMessageDigestBase64(){
		return Base64.encodeBase64String(md);
	}

	

}
